/** @type {HTMLCanvasElement} */
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");
const CANVAS_WIDTH = canvas.width = window.innerWidth;
const CANVAS_HEIGHT = canvas.height = window.innerHeight;


/** @type {HTMLCanvasElement} */
const canvas2 = document.getElementById("collosionCanvas");
const ctx2 = canvas2.getContext("2d");
const CANVAS_WIDTH2 = collosionCanvas.width = window.innerWidth;
const CANVAS_HEIGHT2 = collosionCanvas.height = window.innerHeight;

const makeRavenInterval = 400;// 每间隔500 毫秒生成一次 乌鸦（浏览器电脑性能不同会影响 requestAnimateFrame执行的时间间隔）
let lastTime = 0;
let ravens = [];
let explosions = [];
let timeToNextRaven = 0;
let score = 0; //游戏分数
let isOver = false;

function drawScore(){
    ctx.font = "50px impact";
    ctx.fillStyle = "black";
    ctx.fillText("score:"+score,45,70);
    ctx.font = "50px impact";
    ctx.fillStyle = "white";
    ctx.fillText("score:"+score,50,75);
   
}   

function gameOver(){
    ctx.textAlign = "center"
    ctx.font = "50px impact";
    ctx.fillStyle = "black";
    ctx.fillText("Game Over Your Score Is:"+score,CANVAS_WIDTH/2,CANVAS_HEIGHT/2);
    ctx.font = "50px impact";
    ctx.fillStyle = "white";
    ctx.fillText("Game Over Your Score Is:"+score,(CANVAS_WIDTH/2)+5,(CANVAS_HEIGHT/2)+5    );
}

class Explosion{
    constructor(x,y){
        this.spiritWidth = 200;
        this.spiritHeight = 179;
        this.width = this.spiritWidth * 0.9;
        this.height = this.spiritHeight * 0.9;
        this.x = x - this.width*0.5+30;
        this.y = y - this.height*0.5+30;
        this.frame = 0;
        this.image = new Image();
        this.image.src=("imgs/boom.png"); 
        this.expInterval = 15;
        this.gameFrame = 0;
        this.sound = new Audio("sounds/shoot.wav");
    }

    update(){
       
        this.gameFrame++;
        console.log(this.gameFrame % this.expInterval)
        if(this.gameFrame % this.expInterval == 0){
            this.frame++;
        }
        
    }
    draw(){
        ctx.drawImage(this.image,this.frame*this.spiritWidth,0,this.spiritWidth,this.spiritHeight,this.x,this.y,this.width,this.height);
    }
}

class Raven{
    constructor(){
        this.spiritWidth = 271;
        this.spiritHeight = 194;
        this.sizeTime = Math.random()+0.5;
        this.width = this.spiritWidth*this.sizeTime;
        this.height = this.spiritHeight*this.sizeTime;
        this.image = new Image();
        this.image.src = "imgs/raven.png";
        this.directionX = Math.random()*2+1;
        this.directionY = Math.random()*3-2.5;
        this.isDeleted = false;
        this.x = CANVAS_WIDTH;
        this.y = Math.random()*(CANVAS_HEIGHT-this.height);
        this.frame = 0;
        this.maxFrame = 5;
        this.sinceFlap = 0;
        this.slapInterval = 150;
        this.randomColor = [Math.floor(Math.random()*256),Math.floor(Math.random()*256),Math.floor(Math.random()*256)]
        this.color = `rgb(${this.randomColor[0]},${this.randomColor[1]},${this.randomColor[2]})`
    }
    update(deltaTime){
        this.sinceFlap += deltaTime;
        if(this.x <= 0-this.width){
            this.isDeleted = true;
            isOver = true;
        }
        if(this.sinceFlap >= this.slapInterval){
            this.sinceFlap = 0;
            if(this.frame>4){
                this.frame = 0;
            }else{
                this.frame++;
            }
            
        }
        if(this.y <=0 ||this.y >= CANVAS_HEIGHT-this.height){
            this.directionY = this.directionY * -1;
        }
        this.y -= this.directionY;
        this.x -= this.directionX;
    }
    draw(){
        // console.log(ctx2);
        ctx2.fillStyle = this.color;
        ctx2.fillRect(this.x,this.y,this.width,this.height);
        ctx.drawImage(this.image,this.frame*this.spiritWidth,0,this.spiritWidth,this.spiritHeight,this.x,this.y,this.width,this.height);
    }
}

canvas.addEventListener("click",e=>{
   //通过相同的鼠标位置 获取碰撞画布上 点击的 背景的 颜色信息，并通过颜色信息判定，是点了哪一个raven
   // 获取指定矩形的 像素颜色信息 getImageDate(起始x，起始y，矩形宽，高
   let imageData = ctx2.getImageData(e.offsetX,e.offsetY,1,1);
   let colors = imageData.data;
   let explosion = new Explosion(e.offsetX,e.offsetY);
   explosion.sound.play();
   explosions.push(explosion);
   ravens.forEach(ele=>{
        if(ele.randomColor[0] == colors[0] && ele.randomColor[1] == colors[1] && ele.randomColor[2] == colors[2]){
            ele.isDeleted = true;
            score++;
        }
   })

})

function animate(timestamp){
    ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
    ctx2.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
    let deltaTime = timestamp - lastTime;
    lastTime = timestamp;
    timeToNextRaven += deltaTime;
    if(timeToNextRaven > makeRavenInterval){
        let raven = new Raven();
        ravens.push(raven);
        timeToNextRaven = 0;
    }
  
    drawScore();
    ravens = [...ravens].sort((a,b)=>a.sizeTime - b.sizeTime);
    [...ravens].forEach(ele => {
        ele.update(deltaTime);
        ele.draw(deltaTime);
    });
    explosions.forEach(ele=>{
        ele.update();
        ele.draw();
    })
    ravens = ravens.filter(function(ele){
        return !(ele.isDeleted);
    });
    if(!isOver){
        requestAnimationFrame(animate);
    }else{
        gameOver();
    }
  
}

animate(0);